/**
 * 本项目采用《JFinal 俱乐部授权协议》，保护知识产权，就是在保护我们自己身处的行业。
 * <p>
 * Copyright (c) 2011-2021, jfinal.com
 */

package com.jthink.admin.article;

import com.jthink.common.model.Article;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 博客管理业务层
 */
public class ArticleAdminService {
    private static final int pageSize = 25;
    private Article dao = new Article().dao();


    /**
     * 分页
     */
    public Page<Article> paginate(int pageNumber,int categoryId) {
        if(categoryId>0){
            String sql = "SELECT distinct art.* FROM article_category_mapping aryp left join article art on art.id=aryp.article_id where aryp.category_id=#para(0) order by art.updated desc";
            return  dao.templateByString(sql, categoryId).paginate(pageNumber, pageSize);
        }else{
            return dao.paginate(pageNumber, pageSize, "select *", "from article order by updated desc");
        }

    }

    /**
     * 搜索
     */
    public Page<Article> search(String key, int pageNumber,int categoryId) {
        if(categoryId>0){
            String sql = "SELECT distinct art.* FROM article_category_mapping aryp left join article art on art.id=aryp.article_id where art.title like concat('%', #para(0), '%') and aryp.category_id=#para(1) order by art.updated desc";
            return dao.templateByString(sql, key,categoryId).paginate(pageNumber, pageSize);
        }else{
            String sql = "SELECT distinct art.* FROM article_category_mapping aryp left join article art on art.id=aryp.article_id where art.title like concat('%', #para(0), '%') order by art.updated desc";
            return dao.templateByString(sql, key).paginate(pageNumber, pageSize);
        }

    }

    private Ret validate(Article article, String categoryIds) {
        if (article == null) {
            return Ret.fail( "article 对象不能为 null");
        }
        if (StrKit.isBlank(article.getTitle())) {
            return Ret.fail( "title 不能为空");
        }
        if (StrKit.isBlank(article.getSlug())) {
            return Ret.fail( "简称 不能为空");
        }
        if (StrKit.isBlank(article.getContent())) {
            return Ret.fail( "content 不能为空");
        }
        if (StrKit.isBlank(categoryIds)) {
            return Ret.fail( "分类 不能为空");
        }
        return null;
    }

    /**
     * 创建
     */
    public Ret save(int accountId, String categoryIds, List<Integer> tagIds, Article article) {
        Ret ret = validate(article, categoryIds);
        if (ret != null) {
            return ret;
        }

        article.setAccountId(accountId);
        article.setState(Article.STATE_FALSE); // 默认未发布
        article.setCreated(new Date());
        article.setUpdated(article.getCreated());
        article.setViewCount(0);
        article.save();
        int articleId = article.getId();
        setCategoryIds(articleId, categoryIds, tagIds, true);
        return Ret.ok( "创建成功").set("id", articleId);
    }

    public void incCounts(String categoryId) {
        Db.update("update article_category set counts=counts+1 where id=?", categoryId);
    }

    /**
     * 文章归类
     */
    private int[] setCategoryIds(Integer articleId, String categoryIds, List<Integer> tagIds, boolean isAdd) {
        if (!isAdd) {
            // 删除原有关联
            Db.delete("delete from article_category_mapping where article_id=?", articleId);
        }
        String[] ids = categoryIds.split(",");
        List<Record> list = new ArrayList<>();
        for (String id : ids) {
            Record record = new Record().set("article_id", articleId).set("category_id", id);
            // 增加此分类关联文章数量文章数量
            incCounts(id);
            list.add(record);
        }
        for (int id : tagIds) {
            Record record = new Record().set("article_id", articleId).set("category_id", id);
            list.add(record);
        }
        return Db.batchSave("article_category_mapping", list, 5);
    }

    /**
     * 获取文章分类列表
     */
    public List<String> getCategoryIds(Integer articleId) {
        return Db.query("select CONCAT(category_id,'') from article_category_mapping where article_id=?",
                articleId);
    }

    /**
     * 更新
     */
    public Ret update(Article article, String categoryIds, List<Integer> tagIds) {
        Ret ret = validate(article, categoryIds);
        if (ret != null) {
            return ret;
        }

        article.setUpdated(new Date());
        article.update();
        setCategoryIds(article.getId(), categoryIds, tagIds, false);
        return Ret.ok( "更新成功").set("id", article.getId());
    }

    public List<String> getTagsList(int articleId) {
        return Db.query("SELECT ac.slug FROM article_category_mapping am left join article_category ac on am.category_id=ac.id where article_id=? and type='tag'", articleId);
    }

    /**
     * 发布
     */
    public Ret publish(int id, boolean checked) {
        int state = checked ? Article.STATE_TRUE : Article.STATE_FALSE;
        String sql = "update article set state = ? where id = ?";
        Db.update(sql, state, id);
        return Ret.ok();
    }
    /**
     * 置顶
     */
    public Ret setTop(int id, boolean checked) {
        // 一个意思都是标志位
        int state = checked ? Article.STATE_TRUE : Article.STATE_FALSE;
        String sql = "update article set isTop = ? where id = ?";
        Db.update(sql, state, id);
        return Ret.ok();
    }
    /**
     * 获取
     */
    public Article getById(int id) {
        return dao.findById(id);
    }

    /**
     * 删除
     */
    public Ret deleteById(int id) {
        dao.deleteById(id);
        return Ret.ok( "删除成功");
    }

    public Ret deleteMapping(int id) {
        Db.delete("delete from article_category_mapping where article_id=?", id);
        return Ret.ok( "删除文章关联成功");
    }

}
